﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using ComicQ.Domain.Table;
using ComicQ.Controller;

namespace ComicQ.Dektop.View
{
    /// <summary>
    /// Interaction logic for MemberView.xaml
    /// </summary>
    public partial class MemberView
    {
        private readonly MemberController _memberControl;
        private IList<Member> _members;

        public MemberView()
        {
            InitializeComponent();

            _memberControl = new MemberController();
            _members = _memberControl.GetAllMember();
            dataGridMember.ItemsSource = _members;
        }

        private void RefreshGrid()
        {
            dataGridMember.ItemsSource = null;
            _members = _memberControl.GetAllMember();
            dataGridMember.ItemsSource = _members;
        }

        private void ButtonAddClick(object sender, RoutedEventArgs e)
        {
            var newWindow = new MemberEditorView();

            if (newWindow.ShowDialog() != false)
            {
            }
            else
            {
                RefreshGrid();
            }
        }

        private void ButtonDeleteClick(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dataGridMember.SelectedItem == null)
                    throw new NullReferenceException();

                var member = _members
                        .Where(m => m.Id == _members[dataGridMember.SelectedIndex].Id)
                        .Select(m => m)
                        .Single();

                _memberControl.DeleteMember(member);
                MessageBox.Show("sukses menghapus member");
                RefreshGrid();
            }
            catch (NullReferenceException)
            {
                MessageBox.Show("pilih yang mau didelete");
            }
        }

        private void ButtonEditClick(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dataGridMember.SelectedItem == null)
                    throw new NullReferenceException();

                var newWindow = new MemberEditorView(_members[dataGridMember.SelectedIndex]);

                if (newWindow.ShowDialog() != false)
                {
                }
                else
                {
                    RefreshGrid();
                }
            }
            catch (NullReferenceException)
            {
                MessageBox.Show("pilih yang mau diedit");
            }
        }
    }
}
